package com.devin.dao;

import com.devin.pojo.UserInfo;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.type.JdbcType;

import java.util.List;

public interface UserMapper {
    /*参数name来自登录页login填写的数据，可能有null，所以必须指定jdbcType*/
    @Select("select * from users where username=#{name,jdbcType=VARCHAR}")
    @Results({@Result(id = true,property = "id",column = "id" ,jdbcType=JdbcType.INTEGER),
            @Result(property = "email",column = "email",jdbcType = JdbcType.VARCHAR),
            @Result(property = "username",column = "username",jdbcType = JdbcType.VARCHAR),
            @Result(property = "password",column = "password",jdbcType = JdbcType.VARCHAR),
            @Result(property = "phoneNum",column = "phoneNum",jdbcType = JdbcType.VARCHAR),
            @Result(property = "status",column = "status",jdbcType = JdbcType.INTEGER),
            @Result(property = "roles",column = "id",
                    javaType =List.class,
                    many = @Many(select = "com.devin.dao.RoleMapper.getRolesById"))
    })
    UserInfo getUser(String name) ;

    @Select(" select * from users ")
    List<UserInfo> getUsers();

    @Delete(" delete from users_role where userId=#{userId} ")
    void delUserAndRole(int userId);

    @Delete(" delete from users where id=#{userId}")
    void delUser(int userId);


    @Insert(" insert into users values(null,#{email,jdbcType=VARCHAR},#{username,jdbcType=VARCHAR},#{password,jdbcType=VARCHAR},#{phoneNum,jdbcType=VARCHAR},#{status,jdbcType=INTEGER})")
    @Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id")
    void addUser(UserInfo user);

    @Insert(" insert into users_role values(#{userId,jdbcType=INTEGER},#{roleId,jdbcType=INTEGER}) ")
    void addUserAndRole(@Param("userId") Integer userId,@Param("roleId") Integer roleId);

    @Select(" select * from users where id=#{userId} ")
    @Results({@Result(id = true,property = "id",column = "id",jdbcType = JdbcType.INTEGER),
            @Result(property = "email",column = "email",jdbcType = JdbcType.VARCHAR),
            @Result(property = "username",column = "username",jdbcType = JdbcType.VARCHAR),
            @Result(property = "password",column = "password",jdbcType = JdbcType.VARCHAR),
            @Result(property = "phoneNum",column = "phoneNum",jdbcType = JdbcType.VARCHAR),
            @Result(property = "status",column = "status",jdbcType = JdbcType.INTEGER),
            @Result(property = "roles",column = "id",javaType = List.class,
                    many = @Many(select = "com.devin.dao.RoleMapper.getRolesById")
            )
    })
    UserInfo getUsersDetail(int userId);

    @Update(" delete from users_role where roleId=#{roleId} and userId=#{userId}")
    void delRoleByUserId(@Param("userId") Integer userId, @Param("roleId") Integer roleId);
}
